import sqlite3

def init_db():
    conn = sqlite3.connect('devices.db')
    c = conn.cursor()
    # 创建设备表
    c.execute('''CREATE TABLE IF NOT EXISTS devices
                (id INTEGER PRIMARY KEY, name TEXT, ip TEXT, status TEXT)''')
    devices = [
        ('智能摄像头', '192.168.1.101', '在线'),
        ('智能门锁', '192.168.1.102', '离线'),
        ('智能传感器', '192.168.1.103', '在线'),
        ('智能音箱', '192.168.1.104', '在线'),
        ('智能灯泡', '192.168.1.105', '离线')
    ]
    c.executemany('INSERT INTO devices (name, ip, status) VALUES (?,?,?)', devices)

    # 创建告警信息表
    c.execute('''CREATE TABLE IF NOT EXISTS alerts
                (id INTEGER PRIMARY KEY, count INTEGER)''')
    c.execute('INSERT OR REPLACE INTO alerts (id, count) VALUES (1, 4)')

    # 创建威胁分析表
    c.execute('''CREATE TABLE IF NOT EXISTS threat_analysis
            (id INTEGER PRIMARY KEY, 
             type TEXT, 
             count INTEGER, 
             trend INTEGER)''')
    threat_data = [
        ('DDoS攻击', 23, 12),
        ('异常登录', 15, -5)
    ]
    c.executemany('INSERT INTO threat_analysis (type, count, trend) VALUES (?,?,?)', threat_data)

    # 新增安全事件表
    c.execute('''CREATE TABLE IF NOT EXISTS security_events
                (id INTEGER PRIMARY KEY, 
                 time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                 description TEXT,
                 level TEXT CHECK(level IN ('success', 'warning', 'info', 'error')))''')
    
    # 新增通知表
    c.execute('''CREATE TABLE IF NOT EXISTS notifications
                (id INTEGER PRIMARY KEY,
                 title TEXT,
                 time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                 type TEXT CHECK(type IN ('critical', 'warning')))''')
    
    # 插入示例数据
    events = [
        ('设备固件异常', 'error'),
        ('数据包重放攻击', 'warning'),
        ('未授权访问尝试', 'error'),
        ('协议异常流量', 'warning')
    ]
    c.executemany('INSERT INTO security_events (description, level) VALUES (?,?)', events)
    
    c.executemany('INSERT INTO notifications (title, type) VALUES (?,?)', [
        ('检测到异常流量', 'critical'),
        ('设备离线警告', 'warning')
    ])

    conn.commit()
    conn.close()

if __name__ == '__main__':
    init_db()
